/*
 * @Author: tkp
 * @Date: 2025-01-03 10:48:28
 */
import Vue from 'vue'
import Router from 'vue-router'
import NProgress from 'nprogress'
import store from '@/store/index'
import 'nprogress/nprogress.css'
NProgress.configure({ showSpinner: false })
Vue.use(Router)
const originalPush = Router.prototype.push
Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}
const routers = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/login',
    name: 'login',
    component: resolve => require(['@/views/login/index'], resolve),
    meta: {
      title: '登录',
      path: '/login',
    },
  },
  {
    path: '/404',
    name: 'not_found',
    component: resolve => require(['@/views/not_found/index'], resolve),
    meta: {
      menuName: '404',
      path: '/404',
      index: 1,
    },
  },
  {
    path: '*',
    redirect: '/404'
  }
]
export function initDynamicRoutes() {
  let permission = window.localStorage.getItem('authority.permission') || '[]'
  let permissionList = JSON.parse(permission)
  permissionList.forEach(it => {
    it.path = '/' + it.frontRoute
    it.name = it.frontRoute
    it.component = resolve => require([`@/views${it.frontPath}`], resolve)
  })
  let redirect = '/index'
  if (permissionList.length) {
    redirect = permissionList[0].path
  }
  let param = {
    path: '/home',
    name: 'home',
    redirect: redirect,
    component: resolve => require(['@/layout/home'], resolve),
    children: permissionList
  }
  router.addRoute(param)
}
const router = new Router({
  mode: 'history',
  base: '/permission/',
  routes: routers
})
//挂载路由导航守卫
router.beforeEach(function (to, from, next) {
  let permission = window.localStorage.getItem('authority.permission') || '[]'
  let permissionList = JSON.parse(permission)
  let subTitle = ''
  if (process.env.NODE_ENV == 'development') {
    subTitle = '(开发)'
  }
  if (process.env.NODE_ENV == 'testing') {
    subTitle = '(测试)'
  }
  if (process.env.NODE_ENV == 'preview') {
    subTitle = '(预生产)'
  }
  document.title = '权限管理系统' + subTitle
  NProgress.start()
  let token = store.state.user.token;
  if (permissionList.length == 0) {
    token = false
  }
  if (to.path == '/login') { return next() } else if (!token) { next('/login') } else { next() }
})
router.afterEach((to, from) => {
  NProgress.done()
})
export default router
